<?php
 
namespace Modules\ShopApi\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;
use Tymon\JWTAuth\Exceptions\TokenInvalidException;
use JWTAuth;
use App\Exceptions\ApiException;
class ShopApi
{
    /**
     * Handle an incoming request.
     * php artisan module:make-middleware AdminAuth Admin	
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
		 
		\Config::set('auth.defaults.guard', 'shop_user');
		\Config::set('jwt.ttl', 60);  
		$route_data = $request->route(); 
		$url = str_replace($route_data->getAction()['prefix'] . '/',"",$route_data->uri);
		$url_arr = [
			'auth/login',
			'auth/my',
			'auth/get_about_us',
			'index/get_banner',
			'index/get_live_list',
			'index/swiper_detail',
			'index/pic_detail',
			'index/get_product',
			'index/get_product_detail',
			'index/app_code',
			'category/get_category_one_list',
			'category/get_category_tow_list',
			'cart/get_cart_sum',
			'cart/get_cart_list',
			'upload/upload_file',
			'consult/get_consult_banner',
			'consult/get_consult',
			'consult/get_consult_detail',
			'consult/get_consult_evaluate_list',
			'consult/get_consult_evaluate_one_list',
		];
		$response = $next($request);
		$api_key = $request->header('apikey');
		if($api_key != config('shopapi.api_key')){
			throw new ApiException(['code'=>1101,'msg'=>'apikey错误！']);
		}
		if(in_array($url,$url_arr)){
			return $response;
		}   
		try {
            if (! $user = JWTAuth::parseToken()->authenticate()) {  //获取到用户数据，并赋值给$user   'msg' => '用户不存在'
				throw new ApiException(['code'=>1004,'msg'=>'请先登录！']);
            }
		} catch (TokenExpiredException $e) {
			//token已过期 
			if(!in_array($url,['auth/refresh','auth/logout'])){
				throw new ApiException(['code'=>1003,'msg'=>'token 过期！']);
			}
        } catch (TokenInvalidException $e) {
			//token无效
			if(!in_array($url,['auth/refresh','auth/logout'])){
				throw new ApiException(['code'=>1002,'msg'=>'请先登录！']);
			}
        } catch (JWTException $e) {
			//'缺少token'
			throw new ApiException(['code'=>1001,'msg'=>'请先登录！']);
        }
		return $response;
    }
}
